package hn.cch.servlet;


import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class TomcatServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // super.doGet(req, resp);



        String uri = req.getRequestURI();
        System.out.println("uri:" + uri);


        System.out.println(req.getParameterMap());


        System.out.println();
        resp.getWriter().println("tomcat");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // super.doPost(req, resp);


        String uri = req.getRequestURI();
        System.out.println("uri:" + uri);




        Map parameterMap = req.getParameterMap();
        for (Object object:parameterMap.keySet()) {
            String string = (String) object;
            System.out.println("\t" + string + ":" + req.getParameter(string));
        }


        System.out.println(req.getContentLength());

        // ServletInputStream servletInputStream = req.getInputStream();
        // byte[] bytes = new byte[req.getContentLength()];
        // System.out.println(servletInputStream.read(bytes));
        // System.out.println(new String(bytes));


        BufferedReader bufferedReader = req.getReader();

        // char[] chars = new char[req.getContentLength()];
        // System.out.println(bufferedReader.read(chars));
        // System.out.println(new String(chars));

        System.out.println(bufferedReader.readLine());

        // System.out.println();
        // resp.getWriter().println("tomcat");

        // ServletOutputStream servletOutputStream = resp.getOutputStream();
        // servletOutputStream.write();


        PrintWriter printWriter = resp.getWriter();

        printWriter.write("{\"content\":{\"key\":\"testKey\",\"value\":\"testValue\"},\"datetime\":\"2020-01-01 20:20:20\",\"function\":\"testFunction\"}");

        // printWriter.println();
        // printWriter.print();

    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}
